package com.yt.demo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShiroMain {
    private static final transient Logger log = LoggerFactory.getLogger(ShiroMain.class);

    public static void main(String[] args) {
        log.info("My First Apache Shiro Application");


        //1.
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //2.
        SecurityManager securityManager = factory.getInstance();
        //3.
        SecurityUtils.setSecurityManager(securityManager);

        //登录的主体 subject
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token =
//                new UsernamePasswordToken("litao", "lt321");
        new UsernamePasswordToken("yangtao", "yt123");
        Session session=subject.getSession();
        session.setAttribute("key1","value1");
        try {
            subject.login(token);
            //if no exception, that's it, we're done!
            log.info("用户登录成功");
            //判断用户是否是某个角色
            if ( subject.hasRole( "teacher" ) ) {
                log.info("这是一个老师角色" );
            } else {
                log.info( "不是老师" );
            }
            //判断用户是否拥有某个权限
            if ( subject.isPermitted( "user:select1" ) ) {
                log.info("用户拥有这个权限");
            } else {
                log.info("用户没有这个权限.");
            }
            subject.checkPermission("user:select1");
        } catch (UnknownAccountException uae) {
            //username wasn't in the system, show them an error message?
            log.error("UnknownAccountException",uae);
        } catch (IncorrectCredentialsException ice) {
            log.error("IncorrectCredentialsException",ice);
            //password didn't match, try again?
        } catch (LockedAccountException lae) {
            log.error("LockedAccountException",lae);
            //account for that username is locked - can't login.  Show them a message?
        } catch (AuthenticationException ae) {
            //unexpected condition - error?
            log.error("AuthenticationException",ae);
        }

        subject.logout();
        System.exit(0);
//        org.apache.shiro.authc.credential.Md5CredentialsMatcher
    }
}
